﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace KylinORM.Data.Transaction
{
    /// <summary>
    /// 数据库事务管理
    /// </summary>
    public class TransactionManager
    {
        /// <summary>
        /// 委托链
        /// </summary>
        private Queue<Action<IDbCommand>> action = new Queue<Action<IDbCommand>>();

        private TransactionManager()
        {
        }
        /// <summary>
        /// 定义一个新事务
        /// </summary>
        public static TransactionManager Define()
        {
            return new TransactionManager();
        }
        /// <summary>
        /// 将指定的操作加入事务
        /// </summary>
        /// <param name="work"></param>
        /// <returns></returns>
        public TransactionManager AddMethod(Action<IDbCommand> work)
        {
            this.action.Enqueue(work);
            return this;
        }
        /// <summary>
        /// 执行事务
        /// </summary>
        public void Commit()
        {
            IDbConnection connection = DataProvider.GetInstance().CreateConnection();
            using (connection)
            {
                connection.Open();
                IDbTransaction transaction = connection.BeginTransaction();
                IDbCommand cmd = connection.CreateCommand();
                cmd.Transaction = transaction;

                try
                {
                    while (this.action.Count > 0)
                    {
                        this.action.Dequeue()(cmd);
                    }
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

    }
}
